package com.fc.mall.mongo.util;

import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static org.springframework.data.mongodb.core.query.Query.query;

public class MongoUtils {
    private MongoUtils() {
    }

    public static <T> Slice<T> getSlice(MongoTemplate mongoTemplate, Class<T> type,
                                        Criteria criteria, int page, int pageSize) {
        return getSlice(mongoTemplate, type, criteria, page, pageSize, null);
    }

    public static <T> Slice<T> getSlice(MongoTemplate mongoTemplate, Class<T> type,
                                        Criteria criteria, int page, int pageSize, Sort sort) {
        Query q = query(criteria);
        Pageable pageable = PageRequest.of(page > 0 ? page : 0, pageSize);
        q.with(pageable).limit(pageSize + 1);
        if (sort != null) {
            q.with(sort);
        }
        List<T> results = mongoTemplate.find(q, type);
        boolean hasNext = results.size() > pageSize;
        return new SliceImpl<>(hasNext ? results.subList(0, pageSize) : results, pageable, hasNext);
    }

    public static <T> Page<T> getPage(MongoTemplate mongoTemplate, Class<T> type,
                                      Criteria criteria, int page, int pageSize, Sort sort) {
        Query q = query(criteria);

        Pageable pageable = PageRequest.of(page > 0 ? page : 0, pageSize);
        long count = mongoTemplate.count(q, type);

        if (count == 0) {
            return new PageImpl<>(new ArrayList<>(), pageable, count);
        }

        q.with(pageable).limit(pageSize + 1);
        if (sort != null) {
            q.with(sort);
        }
        List<T> results = mongoTemplate.find(q, type);
        return new PageImpl<>(results, pageable, count);
    }

    public static String generateId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
